/**
 * Copyright (c) 2018, Alex. All rights reserved.
 */
package com.oschina.bottle.coder.digest;

import com.oschina.bottle.coder.CoderException;
import com.oschina.bottle.common.constants.Charset;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * 摘要算法
 *
 * 编码方式采用UTF-8
 *
 * @author <a href="mailto:zhongchao@gegejia.com">zhong</a>
 * @version 1.0 2018/1/4
 * @since 1.0
 */
public class DigestCoder {

    private DigestAlgorithm algorithm;

    public DigestCoder(DigestAlgorithm algorithm) {
        this.algorithm = algorithm;
    }

    public byte[] encrypt(byte[] data) {
        MessageDigest messageDigest = null;
        try {
            messageDigest = MessageDigest.getInstance(algorithm.getName());
        } catch (NoSuchAlgorithmException e) {
            throw new CoderException("支持算法：%s", algorithm.getName());
        }
        messageDigest.update(data);
        return messageDigest.digest();
    }

    public String encrypt(String data) {
        try {
            return toHexStr(encrypt(data.getBytes(Charset.UTF8)));
        } catch (UnsupportedEncodingException e) {
            throw new CoderException("编码异常，格式：%s", Charset.UTF8);
        }
    }

    /**
     * 转换成15进制
     */
    private String toHexStr(byte[] bytes) {
        StringBuffer hex = new StringBuffer();
        //把数组每一字节换成16进制连成md5字符串
        int digital;
        for (int i = 0; i < bytes.length; i++) {
            digital = bytes[i];

            if (digital < 0) {
                digital += 256;
            }
            if (digital < 16) {
                hex.append("0");
            }
            hex.append(Integer.toHexString(digital));
        }
        return hex.toString();
    }
}
